package com.dexilaonian.utils;


import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.dexilaonian.MainActivity;
import com.dexilaonian.MyApplication;
import com.dexilaonian.exception.ApiException;
import com.dexilaonian.ui.MyRecyclerViewOnclickInterface;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.builder.PostStringBuilder;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.IDN;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;

import static com.dexilaonian.utils.Constant.NO_NET;
import static com.dexilaonian.utils.Constant.SERVER_ERROR;
import static java.lang.String.valueOf;


public class Okhttp {
    private static String key;
    private static final String TENANTID = "TenantId";
    private static final String TENANTID_VALUE = "00000000-0000-0000-0000-000000000000";
    private static final String AUTHORIZATION = "Authorization";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    /**
     * 目标文件存储的文件夹路径
     */
    private static String destFileDir = FileUtils.getSDCardPath();
    public static String tokenId;
    private static String myKey;


    public static void get(final String url, Map param, final CallBac callBac) {
        boolean netState = NetUtil.isNetworkAvailable(MyApplication.getInstance());
        if (!netState) {
            callBac.onNoNetwork(NO_NET);
            return;
        }
        String mUrl = null;
        //判断是否有参数
        if (param == null) {
            mUrl = url;
        } else {
            mUrl = url + "?" + getUrlParamsByMap(param);
            Logutil.e("Param=" + param);
        }

        GetBuilder builder = OkHttpUtils
                .get()
                .url(mUrl)
                .addHeader(TENANTID, TENANTID_VALUE);
        builder.build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("服务器异常=" + e.getMessage());
                        callBac.onError(call, e, SERVER_ERROR, id);
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("返回信息=" + response);
                        callBac.onResponse(response, id);
                    }
                });
    }

     // put请求

    public static void put(final String url, final Map param, final CallBac callBac) {
        boolean netState = NetUtil.isNetworkAvailable(MyApplication.getInstance());
        if (!netState) {
            callBac.onNoNetwork(NO_NET);
            return;
        }
        RequestBody body = null;
        if (param != null) {
            body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), getParam(param));
        }

        if (body == null) return;

        OkHttpUtils.put()
                .url(url)
                .requestBody(body)
                .addHeader(TENANTID, TENANTID_VALUE)
                .addHeader(AUTHORIZATION, "Bearer " + getTokenId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + getParam(param));
                        Logutil.e("服务器异常=" + e.getMessage());
                        callBac.onError(call, e, SERVER_ERROR, id);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + getParam(param));
                        Logutil.e("返回信息=" + response);
                        callBac.onResponse(response, id);
                    }
                });
    }

    public static void putJSON(final String url, final JSONObject param, final CallBac callBac) {
        boolean netState = NetUtil.isNetworkAvailable(MyApplication.getInstance());
        if (!netState) {
            callBac.onNoNetwork(NO_NET);
            return;
        }
        RequestBody body = null;
        if (param != null) {
            body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param.toString());
        }
        if (body == null) {
            return;
        }
        OkHttpUtils.put()
                .url(url)
                .requestBody(body)
                .addHeader(TENANTID, TENANTID_VALUE)
                .addHeader(AUTHORIZATION, "Bearer " + getTokenId())
                .build()

                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + param.toString());
                        Logutil.e("服务器异常=" + e.getMessage());
                        callBac.onError(call, e, SERVER_ERROR, id);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + param.toString());
                        Logutil.e("返回信息=" + response);
                        callBac.onResponse(response, id);
                    }
                });
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("charset","utf-8");
            conn.setRequestProperty("Authorization","Bearer " + getTokenId());
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            Toast.makeText(MyApplication.getInstance(),"发送 POST 请求出现异常！"+e,Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
        Log.e("eee", result);
        return result;
    }


    /**
     * 获取tokenid
     */
/*    public static String getTokenId() {

        if (TextUtils.isEmpty(tokenId)) {
         //   tokenId = MyApplication.sp.getString("tokenid", "");
        }
        return tokenId;
    }*/
  /*  public static void postString1(boolean istokenId, final String url, final Map param, final CallBac callBac) {
        boolean netState = NetUtil.isNetworkAvailable(MyApplication.getInstance());
        if (!netState) {
            callBac.onNoNetwork(NO_NET);
            return;
        }
        PostStringBuilder builder = OkHttpUtils.postString()
                .url(url)
                .addHeader(TENANTID, TENANTID_VALUE);
        //需要tokenid
        if (istokenId) {
            //my 没有执行里面好像
            Logutil.e("我的tokenid=" + getTokenId());

            builder.addHeader(AUTHORIZATION, "Bearer " + getTokenId());
        }
        builder.content(getParam(param))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + getParam(param));
                        Logutil.e("服务器异常=" + e.getMessage());
                        callBac.onError(call, e, SERVER_ERROR, id);
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + getParam(param));
                        Logutil.e("返回信息=" + response);
                        callBac.onResponse(response, id);
                    }
                });
    }*/
    /**
     * 获取tokenid
     */
    public static String getTokenId() {
        if (TextUtils.isEmpty(key)) {
            myKey = PreferencesUtil.getString(MainActivity.getContext(),
                    Constant.KEY);
        }
        return myKey;
    }


    public static void postString(boolean istokenId, final String url, final Map<String, String> param, final CallBac callBac) {
        PostFormBuilder builder = OkHttpUtils.post().url(url);
        //需要tokenid
        if (istokenId) {
            Logutil.e("我的tokenid=" + getTokenId());
            builder.addHeader(AUTHORIZATION, "Bearer " + getTokenId());
            builder.addHeader("Content-Type", "application/json; charset=utf-8");
        }
        for (Map.Entry<String, String> entry : param.entrySet()) {
            Logutil.e("参数===key =" + entry.getKey() + " 参数===value==" + entry.getValue());
            builder = builder.addParams(entry.getKey(), entry.getValue());
        }
        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Logutil.e("URL=" + url);
                Logutil.e("参数=" + getParam(param));
                Logutil.e("服务器异常=" + e.getMessage());
                callBac.onError(call, e, SERVER_ERROR, id);
            }

            @Override
            public void onResponse(String response, int id) {
                Logutil.e("URL=" + url);
                Logutil.e("参数=" + getParam(param));
                Logutil.e("返回信息=" + response);
                callBac.onResponse(response, id);
            }
        });
    }
     // 传json

    public static void postJSON(boolean istokenId, final String url, final JSONObject json, final CallBac callBac) {
        boolean netState = NetUtil.isNetworkAvailable(MyApplication.getInstance());
        if (!netState) {
            callBac.onNoNetwork(NO_NET);
            return;
        }

        PostStringBuilder builder = OkHttpUtils.postString()
                .url(url)
                .addHeader(TENANTID, TENANTID_VALUE);

        //需要tokenid
        if (istokenId) {
            Logutil.e("我的tokenid=" + getTokenId());
            builder.addHeader(AUTHORIZATION, "Bearer " + getTokenId());

        }


        builder.content(json.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + json.toString());
                        Logutil.e("服务器异常=" + e.getMessage());
                        callBac.onError(call, e, SERVER_ERROR, id);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("参数=" + json.toString());
                        Logutil.e("返回信息=" + response);
                        callBac.onResponse(response, id);
                    }
                });
    }
     // post上传文件
    public static void postFile(final String url, File file,final Map<String, String> param, final CallBac callBac) {
        OkHttpUtils.post()//
                .addFile("file", file.getName(), file)//
                .url(url)
                .build()//
                .execute(new StringCallback() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("服务器异常=" + e.getMessage());
                        callBac.onError(call, e, SERVER_ERROR, id);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Logutil.e("URL=" + url);
                        Logutil.e("返回信息=" + response);
                        callBac.onResponse(response, id);
                    }
                });
    }
   public static void downloadFile(String url, String fileName, final FileCallBac callBac) {
        //判断网络状态
        boolean netState = NetUtil.isNetworkAvailable(MyApplication.getInstance());
        if (!netState) {
            callBac.onNoNetwork(NO_NET);
            return;
        }
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(destFileDir, fileName) {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        callBac.onError(call, e, id);
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        callBac.onResponse(response, id);
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        callBac.inProgress(progress, total, id);
                    }
                });
    }

    private static String getParam(Map map) {
        JSONObject parms_json = new JSONObject();
        if (map == null || map.size() == 0) {
            return parms_json.toString();
        }
        Set<String> keys = map.keySet();

        for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
            try {
                String key = (String) it.next();
                String value = (String) map.get(key) + "";  //如果这里报错了,请传入字符串
                parms_json.put(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return parms_json.toString();
    }

    //文件回调方法
    public interface FileCallBac {
        void onNoNetwork(String state);

        void onError(Call call, Exception e, int id);

        void onResponse(File response, int id);

        void inProgress(float progress, long total, int id);
    }


    //字符串回调接口
    public interface CallBac{

        void onError(Call call, Exception e, String state, int id);

        void onResponse(String response, int id);

        void onNoNetwork(String state);
    }


    //Object回调接口
    public interface ObjectCallBac<T> {

        void onError(Call call, Exception e, int id);

        void onResponse(T response, int id);

        void onNoNetwork(String state);
    }

    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }
    /**
     * post上传文件
     */
    public static void postFileParams(final String url, final File file, final Map params, final CallBac callBac) {
        if (params != null) {
            // param.put("istest", 1);
            String paramsByMap = getUrlParamsByMap(params);

        }
        OkHttpUtils.post()
                .addFile("image", file.getName(), file)
                .url(url)
                .params(params)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Logutil.e("URL=" + url);
                Logutil.e("文件的名称=" + file.getName());
                Logutil.e("参数=" + params.toString());
                Logutil.e("服务器异常=" + e.getMessage());
              // callBac.onError(call, e.getMessage(), id);
            }

            @Override
            public void onResponse(String response, int id) {
                Logutil.e("URL=" + url);
                Logutil.e("文件的名称=" + file.getName());
                Logutil.e("参数=" + params.toString());
                Logutil.e("返回信息=" + response);
                callBac.onResponse(response, id);
            }
        });
    }
}
